﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Model验证器.Controllers
{
    [Route("[controller]/[action]")]
    public class DefaultController : ControllerBase
    {
        public Models.User Index(Models.User user)
        {
            if (ModelState.IsValid == false)
            {
                String msg = "\r\n";
                foreach (var v in ModelState)
                {
                    foreach (var err in v.Value.Errors)
                    {
                        msg += v.Key + ":" + err.ErrorMessage + "\r\n";
                    }
                }
                throw new Exception(msg);
            }

            Test(new Models.Group()
            {
                GroupCode = "",
                GroupName = "tesetfdafdsafdsafds"
            });

            return user;

        }


        [NonAction]
        public Models.Group Test(Models.Group group)
        {
            ValidationContext context = new ValidationContext(group);
            List<ValidationResult> errors = new List<ValidationResult>();
            if (Validator.TryValidateObject(group, context, errors, true) == false)
            {
                string msg = "\r\n";
                foreach (var err in errors)
                {
                    foreach(var m in err.MemberNames)
                    {
                        msg += m + ",";
                    }
                    msg += err.ErrorMessage+ "\r\n";
                }
                throw new Exception(msg);
            }
            return group;
        }

    }
}